<?php

namespace App\Http\Controllers\api\orders;


use App\Common\statement\CommonStatement;
use App\Http\Controllers\api\base\BaseController;
use App\Http\Requests\base\IdRequest;
use App\Http\Requests\goods\EvaluateRequest;
use App\Http\Resources\orders\OrderDetailResource;
use App\Http\Resources\orders\OrdersPageCollection;
use App\Models\goods\Order;
use App\Models\goods\OrderDetail;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Flex\Express\ExpressBird;
use Illuminate\Support\Facades\DB;

class OrdersController extends BaseController
{



    /**
     * 我的订单列表
     * @param Request $request
     * @return mixed
     */
    public function orders(Request $request)
    {

        $map['user_id'] = $this->user_id;

        if (is_numeric($request->status)){
            $map['status'] = $request->status;
        }

        if (!empty($request->keyword)){
            $map[] = ['goods_name','like',"%{$request->keyword}%"];
        }

        $sql = Order::where($map);

        $rows = $sql->orderByDesc('id')->with('details')->paginate();

        return success( new OrdersPageCollection($rows) );
    }

    public function detail(IdRequest $request)
    {

        $map['id'] = $request->id;
        $map['user_id'] = $this->user_id;

        $order = Order::where($map)->with('details')->firstOrFail();

        return success( new OrderDetailResource($order) );
    }

    /**
     * 退款申请
     */
    public function refund(IdRequest $request)
    {
        $map['user_id'] = $this->user_id;
        $map['id']      = $request->id;

        $order = Order::where($map)->firstOrFail();

        if (!in_array($order->status,CommonStatement::order_refund_status)){
            return error('订单状态不允许退款!');
        }

        DB::beginTransaction();
        try {

            if ($order->status == 0){//未付款取消  直接退回
                $order->delete();
                $msg = "取消成功";
            }else{
                $msg = '提交成功,请耐心等待管理员审核';
                $order->status = 5;
                $order->reason = $request->reason;
                $order->save();
            }

            DB::commit();
        }catch (\Exception $e){

            DB::rollBack();
            return error($e->getMessage());
        }

        return successWithMsg($msg);

    }

    public function cancel(IdRequest $request)
    {
        $map['user_id'] = $this->user_id;
        $map['id']      = $request->id;

        $order = Order::where($map)->firstOrFail();

        if (!in_array($order->status,CommonStatement::order_cancel_status)){
            return error('订单状态不允许取消!');
        }

        DB::beginTransaction();
        try {
            $msg = "取消成功";
            $order->status = -1;
            $order->save();

            DB::commit();
        }catch (\Exception $e){

            DB::rollBack();
            return error($e->getMessage());
        }

        return successWithMsg($msg);

    }

    /**
     * 确认收货
     */
    public function confirm(IdRequest $request)
    {
        $map['id'] = $request->id;
        $map['user_id'] = $this->user_id;
        $order = Order::where($map)->firstOrFail();

        if ($order->status != 2){
            return error("订单状态不能收货!");
        }

        $order->finish_at = Carbon::now()->toDateTimeString();
        $order->status = 3;
        $result = $order->save();

        if ($result){
            return successWithMsg("确认收货成功!");
        }
        return error("操作失败!");

    }


    /**
     * 确认
     */
    public function signFor(IdRequest $request)
    {
        $order = Order::findOrFail($request->id);
        if ($order->user_id != $this->user_id){
            return error("只能签收您自己的货物!");
        }
        if ($order->is_sign_for){
            return error("已签收!");
        }

        $order->is_sign_for = 1;
        $order->save();
        return successWithMsg("签收成功");

    }
    



















    /**
     * 物流动态信息
     */
    public function express(IdRequest $request)
    {

        $map['id'] = $request->id;
        $map['user_id'] = $this->user_id;

        $order = Order::where($map)->firstOrFail();

        $arr['goods_img'] = $order->details[0]->goods->img;
        $arr['nu'] = $order->nu;
        $arr['kd'] = getExpresses()[$order->nu_code];

        $express = new ExpressBird(config('app.express.id'),config('app.express.key'));

        $expressCode = $order->nu_code;
        $expressSn = $order->nu;
        try{
            $info = $express->track($expressSn, $expressCode); //快递单号 物流公司编号 订单编号(选填)
        }catch (\Exception $e){
            return error("查询失败:".$e->getMessage(),$arr);
        }

        return success(array_merge($arr,json_decode($info,true)));

    }

    /**
     * 商品评价
     */
    public function evaluate(EvaluateRequest $request)
    {
        $map['id'] = $request->id;

        if ($request->type == 2){//对所有商品评价
            $map['user_id'] = $this->user_id;

            $order = Order::where($map)->firstOrFail();
        }else{
            $orderDetail = OrderDetail::where($map)->firstOrFail();
            $order = $orderDetail->order;
            $map1['order_id'] = $orderDetail->order_id;
            $map1[] = ['evaluate','!=',''];
            $count = OrderDetail::where($map1)->count();
        }

        $imgs = $request->imgs?? [];

        DB::beginTransaction();
        try{
            if ($request->type == 2){
                OrderDetail::whereOrderId($order->id)->update(['evaluate' => $request->evaluate,'imgs'=>$imgs]);
            }else{
                if ($count + 1 == $order->details->count()){
                    $order->is_evaluate = 1;
                    $order->save();
                }
                $orderDetail->evaluate = $request->evaluate;
                $orderDetail->imgs = $imgs;
                $orderDetail->save();
            }

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());
        }
        return successWithMsg("评价成功");

    }
    

}
